#! /usr/bin/python
#-*- coding: UTF-8 -*-


def useJoin():
    strlist = ["haha", "12312", "rewnhe", "jiuliqiankun", "da"]
    my_string = " "
    str = ""
    print "the string list:", strlist
    for chunk in strlist:
        str += chunk
    #use join to join the string list is better
    print my_string.join(strlist)
    print "mystring using join", my_string
    print str

useJoin()

def trivalExample():
    x, y = 111, 0
    print x, y
    x, y = y, x
    print x, y
    #use 'in' as many as possible
    #use local variables rather than global ones
    #move import to where it is needed
    #use 'while 1' instead of 'while True' to do infinite loop
    #use list  comprehension like below
    evens = [i for i in range(10) if i%2 == 0]
    print evens
    #use 'xrange' instead of 'range' to generate long sequence
    #to save memory
    #use python generator
    chunk = (1000 * i for i in range(1000))
    print chunk
    print chunk.next()
    print chunk.next()
    print chunk.next()

    #use itertools
    import itertools
    iter = itertools.permutations([1,2,3])
    print list(iter)

    #binary search
    import bisect
    mylist = [i*2 for i in xrange(1000000)]
    bisect.insort(mylist, 5)
    print bisect.bisect(mylist, 1000)
    print 100034 in mylist
    #use set or dict when you search data frequently
    myset = set(mylist)
    print 200024 in myset
    #the list in python is implemented as an array, so when
    #insert be careful, use 'deque' when you need insert head
    import Queue
    myqueue = Queue.Queue()
    #use python wraps
    from functools import wraps
    def memo(f):
        cache = {}
        #to use 反射
        @wraps(f)
        def wrap(*arg):
            if arg not in cache:
                cache['arg'] = f(*arg)
                return cache['arg']
        return wrap

    @memo
    def fib(i):
        import time
        if i < 2:
            return 1
        return fib(i-1) + fib(i-2)


    print fib(10)
    print fib.__name__


trivalExample()

